﻿using System;
using System.Data;
using System.Data.Common;

namespace Mind.Data
{
    public class DataAccessTransaction : IDisposable
    {
        public enum Status
        {
            Running,
            RolledBack,
            Commited
        }

        DbConnection _connection;
        DbTransaction _transacao;
        Status _transactionStatus;

        internal DbTransaction GetTransaction()
        {
            return _transacao;
        }

        public Status TransactionStatus
        {
            get
            {
                return _transactionStatus;
            }
        }

        internal DbConnection Connection
        {
            get
            {
                return _connection;
            }
        }

        internal DataAccessTransaction(DbConnection connection, IsolationLevel isolationLevel)
        {
            if (connection.State != ConnectionState.Open)
                connection.Open();

            _connection = connection;
            _transacao = connection.BeginTransaction(isolationLevel);
            _transactionStatus = Status.Running;

        }

        public void Rollback()
        {
            _transacao.Rollback();
            _transactionStatus = Status.RolledBack;

        }

        public void Commit()
        {
            _transacao.Commit();
            _transactionStatus = Status.Commited;

        }



        #region IDisposable Members

        public void Dispose()
        {
            if (_transactionStatus == Status.Running)
                Commit();

            if (_connection.State != ConnectionState.Closed && _connection.State != ConnectionState.Broken)
                _connection.Close();

        }

        #endregion
    }
}